import React, { useEffect,useState } from 'react'
import {useDispatch,useSelector} from "react-redux"
import * as action from "../action"
function Shopcar() {
  const [sum,setSum] = useState(0)
  const [count,setCount] = useState(0)
 const dispatch = useDispatch()
  const store = useSelector((state)=>{
        return {
            ...state.shopreducer
        }
  })
  const checkitem = (id)=>{
     dispatch(action.checkItem(id))
  }
  const addfn = (id)=>{
      dispatch(action.addFn(id))
  }
  const delfn = (id)=>{
    dispatch(action.delFn(id))
  }
  const changeALL = ()=>{
     dispatch(action.changeall())
  }
  useEffect(()=>{ // componetDidmountde,componetddiUpdate,componentWillreciveProps 

     let checkitem = store.shoparr.filter((item,index)=>{
         return item.checked
     })
     console.log(checkitem);
     let sumhe = checkitem.reduce((a,b)=>{
         return a + b.price * b.num
     },0)
     let sumcount = checkitem.reduce((a,b)=>{
         return a + b.num
     },0)
     setCount(sumcount)
     setSum(sumhe)
     return ()=>{
         // 模拟compentwillUNMOUNT
     }
  },[store.shoparr])

  return (
    <div>
        {
            store.shoparr &&   store.shoparr.length ? store.shoparr.map((item,index)=>{
                return <div key={index}>
                    <img src={item.img} alt="" style={{width:"150px"}}/>
                    <h4>标题:{item.tit}</h4>
                    <h4> <input type="checkbox" checked={item.checked} onChange={()=>checkitem(item.id)}/> <button onClick={()=>delfn(item.id)}>--</button> 个数：{item.num} <button onClick={()=>addfn(item.id)}>++</button></h4>
                </div>
            }):"购物车空空"
        }
        <div>
            全选：<input type="checkbox" checked={store.flagall} onChange={changeALL} />总个数：{count}总价：{sum}
        </div>
    </div>
  )
}

export default Shopcar